const authService = require('../services/authService');

/**
 * JWT认证中间件
 * 验证请求头中的token，并将用户信息添加到req.user
 */
const authMiddleware = async (req, res, next) => {
  try {
    // 从请求头获取token
    const authHeader = req.headers.authorization;
    
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return res.status(401).json({
        success: false,
        message: '未提供认证令牌'
      });
    }

    const token = authHeader.substring(7); // 移除 "Bearer " 前缀

    // 验证token
    const decoded = authService.verifyToken(token);
    
    if (!decoded) {
      return res.status(401).json({
        success: false,
        message: '认证令牌无效或已过期'
      });
    }

    // 将用户信息添加到请求对象
    req.user = {
      userId: decoded.userId,
      username: decoded.username,
      realName: decoded.realName,
      employeeId: decoded.employeeId,
      role: decoded.role
    };

    next();
  } catch (error) {
    console.error('认证中间件错误:', error.message);
    return res.status(401).json({
      success: false,
      message: '认证失败'
    });
  }
};

/**
 * 角色验证中间件
 * @param {Array<string>} allowedRoles - 允许的角色列表
 */
const roleMiddleware = (allowedRoles) => {
  return (req, res, next) => {
    if (!req.user) {
      return res.status(401).json({
        success: false,
        message: '未认证'
      });
    }

    if (!allowedRoles.includes(req.user.role)) {
      return res.status(403).json({
        success: false,
        message: '权限不足'
      });
    }

    next();
  };
};

module.exports = {
  authMiddleware,
  roleMiddleware
};


